<template>
  <div class="main-pipeDiameterClassification">
    <div class="layui-tab layui-tab-brief" lay-filter="test-handle">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="search">查询</li>
        <li lay-id="table_result">表结果</li>
        <li lay-id="chart_result">图结果</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div style="display:flex; padding: 15px 0; border-bottom: 1px solid #fff;">
            <div style="width:33%; text-align: center; ">
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="cz-pipeline-type" type="checkbox" value="ZY_JSLINE"> 给水线
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="cz-pipeline-type" type="checkbox" value="ZY_YSLINE"> 雨水线
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="cz-pipeline-type" type="checkbox" value="ZY_GDLINE"> 电力线
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="cz-pipeline-type" type="checkbox" value="ZY_LDLINE"> 路灯线
              </label>
            </div>
            <div style="width:33%; text-align: center; ">
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(1)">全选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(-1)">全不选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(0)">反选
              </button>
            </div>

          </div>
          <div class="layui-row" style="padding: 15px 0; border-bottom: 1px solid #fff;">
            <div class="layui-col-md3 layui-col-md-offset1">
              <label class="btn btn-primary">
                <input type="checkbox" id="spatial"> 空间范围
              </label>
            </div>
            <div class="layui-col-md6">
              <input type="button" class="btn btn-primary" value="矩形" @click="drawRectangle"/>
              <input type="button" class="btn btn-primary" value="面" @click="drawPolygon"/>
              <input type="button" class="btn btn-primary" value="圆" @click="drawCircle"/>
              <input type="button" class="btn btn-primary" value="清除" @click="clearDraw"/>
            </div>
          </div>
          <div class="layui-row">
            <div class="layui-col-md6 layui-col-md-offset1">
              <button type="button" class="layui-btn " style="margin: 3px 0; width: 120px;" @click="flhz()">
                分类汇总
              </button> &nbsp;&nbsp;
              <button type="button" class="layui-btn " style="margin: 3px 0; width: 120px;" @click="qc()">
                清除
              </button> &nbsp;&nbsp;
            </div>
          </div>
        </div>

        <div class="layui-tab-item">
          <table
              id="table"
              data-toggle="table"
              data-height="550"
              data-width="430"
              data-search="true"
              data-pagination="true"
              style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
          >
            <thead id="thead" style="color:#fff;">

            </thead>
          </table>
        </div>
        <div class="layui-tab-item" style="padding:0 10px;">
          <select name="layerSelect" lay-verify="required" id="guanjingtj_layerSelect" v-model="type"
                  @change="rendererChart"
                  style="color: black;width: 100px;height: 25px;"></select>
          <select name="layerSelect" lay-verify="required" v-model="option" @change="rendererChart"  id="guanjingtj_type" style="color: black;width: 100px;height: 25px;margin-left: 10px">
            <option value="count">条数</option>
            <option value="length">长度</option>
          </select>
          <div id="chart_result"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
let from = null
let $table = null
// eslint-disable-next-line no-unused-vars
let openLayer = null
// eslint-disable-next-line no-unused-vars
let openlayerTable = null
let selectEntity = []
// eslint-disable-next-line no-unused-vars
let dataTable = []
let chartData = {}
import clearWindow from "@/components/js/clearWindow";
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import statistics from "@/components/js/statistics";
import guid from "@/components/js/guid";
import randomColor from "@/components/js/randomColor";
export default {
  name: "pipeDiameterClassification",
  components: {},
  data() {
    return {
      type:undefined,
      option:'count'
    };
  },
  mounted() {
    openLayer = null;
    $table && $table.bootstrapTable('destroy')
    $table = null;
    clearWindow()

  },
  methods: {
    qc() {
      this.clearDraw()
      this.allSelect(-1)
      openlayerTable && layui.layer.close(openlayerTable)
      openlayerTable = null
      if ($('#spatial')[0]) $('#spatial')[0].checked = false
    },
    clearDraw() {
      window.window.viewer.dadi.draw.clearDraw();
      for (let i = 0; i < selectEntity.length; i++) {
        selectEntity[i].billboard.image = 'img/marker/mark3.png';
      }
      selectEntity = [];
      from = null;
      // $table.bootstrapTable('destroy')
      $('#layerSelect').html('');
      // $('#thead').html('')
      dataTable = []
    },
    hideLayerContent() {
      this.$emit('hidden')
    },
    showLayerContent() {
      this.$emit('show')
    },
    allSelect(flag) {
      let els = $('.cz-pipeline-type')
      if (flag == 1) {
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = true
        }
      } else if (flag == -1) {
        $('.cz-pipeline-type').attr('checked', false)
      } else { // 反选
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = !element.checked
        }
      }
    },
    drawRectangle() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "rectangle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.showLayerContent()
        }
      });
    },
    drawPolygon() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "polygon",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.showLayerContent()
        }
      });
    },
    drawCircle() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "circle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.showLayerContent()
        }
      });
    },
    flhz() {
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      let els = $('.cz-pipeline-type')
      let pipelineTypes = []
      for (let index = 0; index < els.length; index++) {
        const element = els[index];
        if (element.checked) {
          pipelineTypes.push(element.value)
        }
      }

      if (pipelineTypes.length == 0) {
        layui.layer.alert('至少选择一类管线进行统计！')
        return;
      }

      if ($('#spatial')[0].checked && !drawGeojson) {
        layui.layer.alert('空间统计请绘制范围！')
        return;
      }

      // 求from
      if ($('#spatial')[0].checked && drawGeojson) {
        if (drawGeojson.features[0].properties.type === 'circle') {
          from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
        } else if (drawGeojson.features[0].properties.type === 'polygon') {
          from = turf.feature(drawGeojson.features[0].geometry)
        } else if (drawGeojson.features[0].properties.type === 'rectangle') {
          let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
            a.splice(-1)
            b.splice(-1)
            return a.concat(b)
          })
          from = turf.bboxPolygon(geo)
        }
      }

      let bianli = 0;
      let tableArr = [];
      pipelineTypes.forEach(async item => {
        bianli++;
        let properties = [];
        let mylayer = layersMap.find(l => l.pipelineType === item)

        const r = await fetchData(mylayer.url)
        r.features.forEach(fea => {
          // 空间筛选
          if ($('#spatial')[0].checked && drawGeojson) {

            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, from);
            if (withIntersect) {
              properties.push(fea.properties)
            }
          } else {
            properties.push(fea.properties)
          }
        })

        let res = statistics(properties, '管径', 'SHAPE_Leng')
        let sumCount = 0, sumSum = 0;
        Object.keys(res).forEach(k => {
          sumCount += res[k].count
          sumSum += res[k].sum
          let dh = ''
          if (mylayer.pipelineType.indexOf('POINT') > -1) {
            dh = mylayer.pipelineType.split('_')[1].split('POINT')[0]
          } else {
            dh = mylayer.pipelineType.split('_')[1].split('LINE')[0]
          }
          tableArr.push({
            '层名': mylayer.type,
            '要素代号': dh,
            '管径': k,
            '条数': res[k].count,
            '长度': res[k].sum,
            '总条数': '',
            '总长度': '',
          })
        })
        // 汇总
        tableArr.push({
          '层名': mylayer.type,
          '管径': '',
          '条数': '',
          '长度': '',
          '总条数': '合计：' + sumCount + '条',
          '总长度': '合计：' + sumSum.toFixed(3) + '米',
        })
      })

      function refreshTable(tableArr) {
        $table = $('#table');
        let thead = `<tr>`
        Object.keys(tableArr[0]).forEach(key => {
          thead += `<th data-field="${key}">${key}</th>`
        })
        thead += `</tr>`
        $table.bootstrapTable('destroy')
        $('#thead').html(thead)
        $table.bootstrapTable({
          data: tableArr,
          // eslint-disable-next-line no-unused-vars
          onClickRow: function (row, $element) {
          }
        })
        $table.bootstrapTable('refresh')
      }


      let timer = setInterval(() => {
        if (bianli === pipelineTypes.length) {
          window.clearInterval(timer)
          refreshTable(tableArr)
          layui.element.tabChange('test-handle', 'table_result'); // 切换到：标签3

          // 画charts图
          // let barXAxis = [], barData = []
          chartData = {};
          for (let index = 0; index < tableArr.length; index++) {
            const f1 = tableArr[index]['长度'];
            const f2 = tableArr[index]['总条数'];
            const f3 = tableArr[index]['管径'];
            const f4 = tableArr[index]['层名'];
            const f5 = tableArr[index]['要素代号'];
            const f6 = tableArr[index]['条数'];
            if (f2.trim() === '') {
              if (!chartData[f4]) {
                chartData[f4] = []
              }
              chartData[f4].push({name: f5+'_'+ f3, length_value: f1, count_value: f6})
            }
          }

          let optionHtml = ''
          Object.keys(chartData).forEach(k => {
            optionHtml += `<option value="${k}">${k}</option>`
          })
          $('#guanjingtj_layerSelect').html(optionHtml)

          $('#chart_result').html('')
          this.rendererChart(Object.keys(chartData)[0])

        }
      }, 2000);

    }    ,
    rendererChart(){
      $('#chart_result').html('')
      let k=this.type || Object.keys(chartData)[0]
      this.type=k
      let type=this.option
      let barId = 'chart-bar-' + guid()
      let pieId = 'chart-pie-' + guid()
      // eslint-disable-next-line no-unused-vars
      let color = randomColor()
      $('#chart_result').append(`
            <div id="${barId}" style="width: 400px; height: 350px; float: left;"></div>
            <div id="${pieId}" class="custom-chart" style="width: 400px; height: 350px; float: right;"></div>
        `)
      let optionBar = {
        // 浮动提示框
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: chartData[k].map(f => f.name),
          textStyle: {
            color: 'white' // 设置图例文字颜色为白色
          }
        },
        xAxis: {
          type: 'category',
          data: chartData[k].map(f => f.name),
          axisLine: {
            lineStyle: {
              color: 'white' // 设置 X 轴颜色为白色
            }
          },
          axisLabel: {
            textStyle: {
              color: 'white' // 设置 X 轴标签颜色为白色
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: 'white' // 设置 Y 轴颜色为白色
            }
          },
          axisLabel: {
            textStyle: {
              color: 'white' // 设置 Y 轴标签颜色为白色
            }
          }
        },
        series: [
          {
            data: chartData[k].map(f => {
              return {name: f.name, value: f[type + '_value'], itemStyle: { color: randomColor()}}
            }),
            type: 'bar'
          }
        ]
      };
      let chartBar = echarts.init(document.getElementById(barId))
      chartBar.setOption(optionBar)

      // 饼图
      let optionPie = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c} ({d}%)'
        },
        legend: {
          data: chartData[k].map(f => f.name),
          textStyle: {
            color: 'white' // 设置图例文字颜色为白色
          }
        },
        series: [
          {
            name: '管径',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: chartData[k].map(f => {
              return {value: f[type + '_value'], name: f.name, itemStyle: {color:  randomColor()}}
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      let chartPie = echarts.init(document.getElementById(pieId))
      chartPie.setOption(optionPie)
    }
  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    clearWindow()
  },
}
</script>

<style scoped>
.main-pipeDiameterClassification {
  position: relative;
  height: 100%;
  width: 100%;
}
</style>
<style>
.main-pipeDiameterClassification > div:nth-child(1), .main-pipeDiameterClassification > div:nth-child(2) {
  border-bottom: 1px solid #0aa8e4 !important;
}

.main-pipeDiameterClassification > div:nth-child(3) button {
  background-image: url("../assets/img/button/button.png");
  background-size: 100% 100%;
  background-color: transparent !important;
}

</style>